<?php

namespace App\Http\Controllers\Admin;

use App\Common\Exceptions\AixinException;
use App\Common\Exceptions\AixinExceptionCode;
use App\Common\Model\ShopAccount;
use App\Http\Controllers\Controller;
use App\Model\Admin;
use App\Model\Role;
use App\Model\User;
use App\Service\AdminService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    /**
     * 用户列表页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function users(Request $request)
    {
        $queryStr = $request->querystr;
        $users = User::where('name', 'like', $queryStr.'%')
            ->orWhere('uid', 'like', $queryStr.'%')
            ->with('getPuidName')
            ->orderBy('create_time','desc')
            ->paginate(20);
        return view('admin.user.users', ['users' => $users, 'querystr' => $queryStr]);
    }

    /*
     * 后台管理员重置用户的密码
     */
    public function changePsw(Request $request)
    {
        if($request->has('id')){
            //开始操作数据。
            $rs = ShopAccount::where('id',$request->id)->update(['pay_passwd'=>'']);
            if($rs){
                return ApiResponse([]);
            }else{
                return ApiResponse('','修改失败',1);
            }

        }else{
            throw new AixinException(AixinExceptionCode::MISSING_PARAM);
        }
    }
    /*
     * 后台删除前台用户的功能
     */
    public function deleteUser(Request $request)
    {
        if($request->has('id') && $request->has('uid')){
            //开始操作数据。还有user表中的数据
            DB::beginTransaction();
            try{
                $rs1 = ShopAccount::destroy($request->id);
                $rs2 = \App\Common\Model\User::destroy($request->uid);
                if($rs1 && $rs2){
                    DB::commit();
                    return ApiResponse([]);
                }
            }catch(\Exception $e){
                DB::rollBack();
                return ApiResponse('','删除失败',1);
            }
        }else{
            throw new AixinException(AixinExceptionCode::MISSING_PARAM);
        }
    }


}
